<template>
<div class="choose-userlist">
    <section v-if="config.model !== 'normal'">

    </section>
    <el-dialog custom-class="wlm-form-dialog dialog-table" :visible.sync="dialogTableVisible" @open="dialogGetData">
        <div class="wlm-dialog-fixheader">
            <span class="wlm-dialog-inlenr">链接选择器</span>
        </div>
        <!-- <el-scrollbar> -->
        <div class="wlm-table-content">
            <div class="wlm-dialog-main">
                <div class="flex-row">
                    <el-scrollbar>
                        <div class="goods-menu">
                            <div class="goods-menu-item ellipsis" @click="requestData(item.name, index)" :class="{'is-active':item.name === requestCurrent}" v-for="(item, index) in requestList" :key="index">
                                <!-- <i class="el-icon-circle-close   rate" v-if="tableFormatData.userTable.files.group_id === item.group_id"></i> -->
                                <span>{{item.title}}</span>
                            </div>
                        </div>
                    </el-scrollbar>
                    <el-scrollbar style="width:100%;height: 520px;max-height: 520px;">
                        <div class="goods-list-box">
                            <div class="goods-list-group flex-row flex-warp">
                                <div class="goods-list">
                                        <el-select v-model="tableFormatData.userTable.files.model" placeholder="请选择" @change="filesSerch" style="margin-bottom:10px;" v-if="patSetting.plugin.cgp.open">
                                            <el-option
                                              v-for="item in options"
                                              :key="item.value"
                                              :label="item.label"
                                              :value="item.value">
                                            </el-option>
                                          </el-select>
                                    <div v-if="requestCurrent === 'goods'" class="goods-item flex-row flex-align-c" style="background:rgb(247,247,247)">
                                        <!-- text-danger -->
                                        <div class="item-name">分类名称</div>
                                        <div class="item-grade">分类级别</div>
                                        <div class="item-num">商品数</div>
                                        <div class="item-time" style="width:30%;">创建时间</div>
                                    </div>
                                    <div v-if="requestCurrent === 'coupon'" class="goods-item flex-row flex-align-c" style="background:rgb(247,247,247)">
                                        <!-- text-danger -->
                                        <div class="item-name">优惠券名称</div>
                                        <div class="item-time">满足条件</div>
                                        <div class="item-num">总数/已领取</div>
                                    </div>
                                    <div v-if="requestCurrent === 'keyword'" class="goods-item flex-row flex-align-c" style="background:rgb(247,247,247)">
                                        <!-- text-danger -->
                                        <div class="item-name">回复规则</div>
                                        <div class="item-time">关键词</div>
                                        <div class="item-num">规则内容</div>
                                    </div>
                                </div>
                                <div class="goods-list" v-for="(item, index) in filterTable" :key="index">
                                    <div class="goods-item flex-row flex-align-c" :class="{'is-active': currentRow.includes(item[`${currentId[`${requestCurrent}`]}`]),'is-disabled': hasDisabled(item)}" style="cursor: pointer;" @click="chooseGoods(item[`${currentId[`${requestCurrent}`]}`], item, hasDisabled(item))">
                                        <!-- text-danger -->
                                        <template v-if="requestCurrent === 'goods'">
                                            <div class="item-name">{{item.name}}</div>
                                            <div class="item-grade">{{item.leave==1?'一级':'二级'}}</div>
                                            <div class="item-num text-danger">{{item.goodsnum}}</div>
                                            <div class="item-time" style="width:30%;">{{item.create_time}}</div>
                                        </template>
                                        <template v-if="requestCurrent === 'coupon'">
                                            <div class="item-name line-hide">{{item.name}}</div>
                                            <div class="item-time">
                                                <template v-if="item">
                                                    <el-popover trigger="hover" placement="top">
                                                        <p>
                                                            <couponRender>
                                                                <template slot="title" v-if="item.coupon_type">
                                                                    {{`${item.rule === 0 ? `${coupon_price[`${item.coupon_type}`]['textRule']}${item.rule_min_money}元`:''} ${coupon_price[`${item.coupon_type}`]['textPrev']}`}}
                                                                </template>
                                                                <template slot="price">
                                                                    {{item.coupon_type === 40 ? `${item.min} - ${item.max}` : item.coupon_type === 20 ? item.discount : item.reduce_price}}
                                                                </template>
                                                                <template slot="tail" v-if="item.coupon_type">
                                                                    {{coupon_price[`${item.coupon_type}`]['textLast']}}
                                                                </template>
                                                            </couponRender>
                                                        </p>
                                                        <div slot="reference" class="wlm-table-wrapper">
                                                            <couponRender>
                                                                <template slot="title" v-if="item.coupon_type">
                                                                    {{`${item.rule === 0 ? `${coupon_price[`${item.coupon_type}`]['textRule']}${item.rule_min_money}元`:''} ${coupon_price[`${item.coupon_type}`]['textPrev']}`}}
                                                                </template>
                                                                <template slot="price">
                                                                    {{item.coupon_type === 40 ? `${item.min} - ${item.max}` : item.coupon_type === 20 ? item.discount : item.reduce_price}}
                                                                </template>
                                                                <template slot="tail" v-if="item.coupon_type">
                                                                    {{coupon_price[`${item.coupon_type}`]['textLast']}}
                                                                </template>
                                                            </couponRender>
                                                        </div>
                                                    </el-popover>
                                                </template>
                                            </div>
                                            <div class="item-num">{{`${item.total_num}/${item.receive_num}`}}</div>
                                        </template>
                                        <template v-if="requestCurrent === 'keyword'">
                                            <div class="item-name">{{item.name}}</div>
                                            <div class="item-num text-danger">{{$keyword(item)['keys']}}</div>
                                            <div class="item-time">
                                                <el-popover trigger="hover" placement="top">
                                                    <div class="flex-col">
                                                        <div class="flex-row flex-align-c flex-justify-c">
                                                            <span v-html="$keyword(item)['content']"></span>
                                                        </div>
                                                    </div>
                                                    <div slot="reference" class="name-wrapper">
                                                        <div class="ellips_line2" style="max-height: 51px;overflow: hidden;text-align: center;">
                                                            <span v-html="$keyword(item)['content']"></span>
                                                        </div>
                                                    </div>
                                                </el-popover>
                                            </div>
                                        </template>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>

            </div>
        </div>
        <!-- </el-scrollbar> -->
        <div class="pagination-content flex-row flex-justify-b flex-align-c">
            <el-row class="pagination-btns">
            </el-row>
            <el-pagination style="margin-top:20px;margin-bottom:20px;margin-right: 25px;" :disabled="!hasTableData" @size-change="listPageChange" @current-change="listPageChange" :current-page.sync="tableFormatData.userTable.pagination.page" :page-sizes="tableFormatData.userTable.pagination.pagesizes" :page-size.sync="tableFormatData.userTable.pagination.list_rows" layout="total, sizes, prev, pager, next, jumper" :total="hasTableData?tableFormatData.userTable.pagination.total : 0">
            </el-pagination>
        </div>
        <div class="wlm-dialog-fixfooter">
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="toggle">取 消</el-button>
                <el-button size="small" type="primary" @click="saveChoose">确 定</el-button>
            </span>
        </div>
    </el-dialog>
</div>
</template>

<script>
import {
  goodsclassIndex
} from '@/api/merchandise'
import {
  couponList
} from '@/api/application'
import {
  getReplys
} from '@/api/channel'
import mixins from '@/mixins/mixins'
import defaultConfig from './utils/config'
import power from '@/mixins/power'
// import {
//   tooggleArray
// } from '@/utils/index'
export default {
  mixins: [defaultConfig.mixins, mixins.getters('Table'),power],
  props: {
    defaultConfig: {
      type: Object,
      default: function() {
        return defaultConfig
      }
    },
    isShow: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    'config.choose_type': {
      handler(newData, oldData) {
        if (newData && Array.isArray(newData) && newData.length > 0) {
          const [requestCurrent] = newData
          const copyRequest = [{
            name: 'goods',
            title: '商品分类',
            api: goodsclassIndex
          }, {
            name: 'coupon',
            title: '优惠券',
            api: couponList
          }, {
            name: 'keyword',
            title: '关键词',
            api: getReplys
          }]
          this.requestCurrent = requestCurrent
          const index = copyRequest.findIndex(item => {
            return item.name === requestCurrent
          })

          if (index !== -1) {
            this.tableFormatData.userTable.api.getList = copyRequest[index]['api']
            // console.log(this.requestCurrent, 'this.requestCurrent')
          }
          this.requestList = []
          copyRequest.map((item, index) => {
            if (newData.includes(item.name)) {
              this.requestList.push(item)
            }
          })
          // console.log(this.requestList, newData, 'this.requestList')
        }
      },
      immediate: true,
      deep: false
    }
  },
  data() {
    return {
       options:[
        {value: '',label: '全部'},
        {value: 'shop',label: '商城模式'},
        {value: 'cgp',label: '社区模式'},
        ],
      keywordMap: ['basic', 'images', 'music', 'news', 'video'],
      requestCurrent: 'goods',
      currentId: {
        'goods': 'category_id',
        'coupon': 'coupon_id',
        'keyword': 'id'
      },
      requestList: [],
      defaultProps: {
        children: 'child',
        label: 'name'
      },
      coupon_price: {
        10: {
          textRule: '满',
          textPrev: '减免',
          textLast: '元'
        },
        20: {
          textRule: '满',
          textPrev: '打',
          textLast: '折'
        },
        30: {
          textRule: '满',
          textPrev: '减免',
          textLast: '元'
        },
        40: {
          textRule: '满',
          textPrev: '范围内随机',
          textLast: '元'
        }
      },
      displayData: [],
      menuData: [],
      currentRow: [],
      closable: true,
      dialogTableVisible: false,
      tableFormatData: {
        current: 'userTable',
        userTable: {
          key: 'userTable',
          api: {
            getList: goodsclassIndex,
            noCreate: true
          },
          tableData: [],
          files: {
            get_limit_type: '0',
            ids: [],
            checkall: '0',
            category_id: '',
            model:''
          },
          pagination: {
            page: 1,
            list_rows: 10,
            pagesizes: [10, 20, 50],
            total: 0
          }
        }
      }
    }
  },
  components: {
    couponRender: {
      template: '<span><slot name="title"></slot><span class="text-danger"><slot name="price"></slot></span><slot name="tail"></slot></span>'
    }
  },
  computed: {
    $id() {
      return `${this.currentId[`${this.requestCurrent}`]}`
    },
    $keyword() {
      return function($scope) {
        const result = {
          keys: [],
          content: []
        }
        const { keywords, allreply } = $scope
        this.keywordMap.map(item => {
          if (allreply && allreply[`${item}`]) {
            const { basic, images, music, news, video } = allreply
            switch (item) {
              case 'basic':
                result.content.push(`<span class="text-danger">${basic}</span>条文本`)
                break
              case 'images':
                result.content.push(`<span class="text-danger">${images}</span>条图片`)
                break
              case 'music':
                result.content.push(`<span class="text-danger">${music}</span>条音频`)
                break
              case 'news':
                result.content.push(`<span class="text-danger">${news}</span>条图文`)
                break
              case 'video':
                result.content.push(`<span class="text-danger">${video}</span>条视频`)
                break
            }
          }
        })
        if (keywords.length > 0) {
          keywords.map(item => {
            const { content } = item
            if (content) {
              result.keys.push(content)
            }
          })
        }
        result.keys = result.keys.join(';')
        result.content = result.content.join(';')
        return result
      }
    },
    filterTable() {
      const tableData = this.tableFormatData.userTable.tableData
      const tableDataArr = Object.keys(tableData)
      let result = []
      if (Array.isArray(tableDataArr)) {
        if (this.requestCurrent === 'goods') {
          tableDataArr.map((item, index) => {
            if (Array.isArray(tableData[item]['child'])) {
              tableData[item]['child'].map((childItem, childIndex) => {
                // tableData[item].goodsnum += childItem.goodsnum
                result.push(childItem)
              })
            }
            result.push(tableData[item])
          })
        } else {
          result = tableData
        }
      }
      return result
    },
    hasDisabled(item) {
      return (item) => {
        let hasDisabled = false
        const disabled = this.config.disabled
        if (Array.isArray(disabled) && disabled.length > 0) {
          disabled.map(lableItem => {
            const hasValue = lableItem.reverse ? item[`${lableItem.label}`] !== lableItem.value : item[`${lableItem.label}`] === lableItem.value
            if (hasValue) {
              hasDisabled = true
            }
            return hasValue
          })
        }
        return hasDisabled
      }
    }
  },
  created() {

  },
  methods: {
    dialogGetData() {
      this.tableFormatData.userTable.api.noCreate = false
      this.getTableList()
    },
    toggle() {
      this.dialogTableVisible = !this.dialogTableVisible
      this.$emit('toggleEvt', { isShow: this.dialogTableVisible })
    },
    requestData(name, index) {
      this.requestCurrent = name
      if (typeof index === 'number' && name) {
        this.tableFormatData.userTable.api.getList = this.requestList[index]['api']
        this.filesSerch()
      }
    },
    saveChoose() {
      this.toggle()
      this.output()
      this.$emit('toggleEvt', { isShow: this.dialogTableVisible })
    },
    chooseGoods(ids, item, hasDisabled) {
      if (!hasDisabled) {
        this.currentRow = [ids]
        if (this.currentRow.includes(ids)) {
          this.displayData = [item]
        } else {
          const newIndex = this.displayData.findIndex((displayItem) => {
            return displayItem[this.$id] === ids
          })
          this.displayData.splice(newIndex, 1)
        }
      }
    },
    output() {
      if (Object.prototype.toString.call(this.changeEvt) === '[object Function]') {
        this.changeEvt({ currentRow: this.currentRow, displayData: this.displayData, key: 'ChooseCategories', type: this.requestCurrent }, this.updateConfig.bindKey)
      }
      // this.displayData = this.currentRow
      console.log(this.displayData)
    }
  }
}
</script>

<style lang="scss" scoped>
.choose-userlist {
    $item-height: 40px;
    $item-font: 12px;
    font-size: 14px;
    margin-bottom: 10px;

    /deep/ .pagination-content .el-input {
        width: 100px;
    }

    .tag-list .el-tag {
        width: auto;
        white-space: nowrap;
        text-overflow: ellipsis;

        &+.el-tag {
            margin-left: 5px;
        }
    }

    .wlm-dialog-main {
        max-height: 520px;
    }

    /deep/ .is-horizontal {
        display: none;
    }

    /deep/ .el-scrollbar__view {
        font-size: 16px;
    }
    .line-hide {
        white-space: nowrap;
    }
    .line-hide,
    .two-line-hide {
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .goods-menu {
        width: 200px;
        max-height: 520px;
        padding-right: 65px;
        padding-bottom: 12px;
        overflow-x: hidden;

        .goods-menu-item {
            position: relative;
            overflow: visible;
            cursor: pointer;
            text-align: center;
            background: transparent;
            margin-bottom: 15px;
            font-size: 12px;
            color: #000;
            padding: 10px;
            border-radius: 5px;
            width: 100%;

            &.is-active {
                .el-icon-circle-close   {
                    top: -10px;
                    right: -10px;
                }

                font-size: 14px;
                border-color: transparent;
                color: #409eff !important;
                background: rgb(195, 225, 254) !important;
            }
        }

        /deep/ .el-tree-node__content {
            .el-tree-node__expand-icon:not(.is-leaf) {
                color: #409eff !important;
            }

            &:hover {
                color: #fff;
                background: #409eff !important;

                .el-tree-node__expand-icon:not(.is-leaf) {
                    color: #fff !important;
                }
            }
        }

        /deep/ .el-tree-node:focus>.el-tree-node__content {
            color: #fff;
            background: #409eff !important;

            .el-tree-node__expand-icon:not(.is-leaf) {
                color: #fff !important;
            }
        }

        /deep/ .el-tree-node.is-current:not(.is-expanded) {
            color: #fff;
            background: #409eff !important;

            .el-tree-node__expand-icon:not(.is-leaf) {
                color: #fff !important;
            }
        }

        /deep/ .el-tree-node.is-current.is-expanded>.el-tree-node__content {
            color: #fff;
            background: #409eff !important;

            .el-tree-node__expand-icon:not(.is-leaf) {
                color: #fff !important;
            }
        }
    }

    .goods-list-box {
        width: 100%;
        min-height: 520px;
        padding: 20px 20px 30px;
        margin-top: -20px;
        border-left: 1px solid #f2f2f2;

        /deep/ .goods-serch {
            position: relative;
            margin-bottom: 20px;
            text-align: left;

            .el-input__inner {
                width: 200px;
                border: none;
                background: rgb(237, 237, 237);
                border-radius: 20px;
                font-size: 12px;
            }

            i {
                cursor: pointer;
                left: 200px;
                margin-left: -35px;
                font-size: 20px;
            }
        }

        .goods-list {
            width: 100%;

            &:not(:nth-last-child(1)) {
                padding-bottom: 14px;
            }

            .goods-item {
                border: 1px solid #d8d1d1;
                margin-right: 20px;
                padding: 8px 10px;
                border-radius: 5px;

                &.is-disabled {
                    color: #ffffff;
                    background: #c0c4cc;
                    cursor: not-allowed !important;

                    .wlm-table-wrapper {
                        cursor: not-allowed !important;
                    }
                }

                .item-name {
                    width: 30%;
                    font-size: $item-font;
                    height: $item-height;
                    line-height: $item-height;
                }

                .item-num {
                    width: 20%;
                    font-size: $item-font;
                    height: $item-height;
                    line-height: $item-height;
                }
                .item-grade {
                    width: 20%;
                    font-size: $item-font;
                    height: $item-height;
                    line-height: $item-height;
                }

                .item-time {
                    width: 50%;
                    font-size: $item-font;
                    height: $item-height;
                    line-height: $item-height;
                }

                &.is-active {
                    border: 1px solid #409eff !important;
                }
            }
        }
    }
}
</style>
